package com.xaicode.template.batch.job.launcher;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobInstanceAlreadyExistsException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.JobOperator;
import org.springframework.batch.core.launch.NoSuchJobException;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author beborn
 * @date 2022/2/15 0015 10:41
 */
@RestController
@RequestMapping("job")
public class JobLauncherController {

    @Resource
    private Job launcherJob;

    @Resource
    private JobLauncher jobLauncher;

    @Resource
    private JobOperator jobOperator;

    @GetMapping("launcher/{message}")
    public String launcher(@PathVariable String message) throws JobInstanceAlreadyCompleteException, JobExecutionAlreadyRunningException, JobParametersInvalidException, JobRestartException {
        JobParameters parameters = new JobParametersBuilder()
                .addString("message", message)
                .toJobParameters();
        // send params to launcher job
        jobLauncher.run(launcherJob, parameters);
        return "success";
    }

    @GetMapping("operator/{message}")
    public String operator(@PathVariable String message) throws JobInstanceAlreadyExistsException, NoSuchJobException, JobParametersInvalidException {
        // send by kv
        jobOperator.start("launcherJob", "message=" + message);
        return "success";
    }

}
